package cn.edu.hznu.notebook.controller;

import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.hznu.notebook.entity.Notebook;
import cn.edu.hznu.notebook.entity.ResponseResult;
import cn.edu.hznu.notebook.entity.User;
import cn.edu.hznu.notebook.service.NotebookService;

@RestController
@RequestMapping(value = "notebook")
public class NotebookController {
	
	@Autowired
	NotebookService notebookService;
	
	@RequestMapping(value = "/list")
	public List<Notebook> getNotebooks(HttpSession session) {
	    Object user = session.getAttribute("user");
	    if (user != null) {
	    	return this.notebookService.getNotebooksByUser((User)user);
	    } else {
	    	return null;
	    }
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResponseResult addNotebook(
			@RequestParam(value = "notebookName", required = true) String notebookName,
			HttpSession session) {
			ResponseResult result = new ResponseResult();
			result.setSucceeded(true);
			Notebook notebook = new Notebook();
			notebook.setNotebookName(notebookName);
			notebook.setNoteSum(0);
			Optional.ofNullable(session.getAttribute("user"))
					.ifPresent(user -> notebook.setUser((User)user));
			try {
				this.notebookService.addNewNotebook(notebook);
			} catch (Exception e) {
				result.setSucceeded(false);
				result.setMessage(e.getMessage());
			}
			return result;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public ResponseResult upateNotebook(
			@PathVariable Integer id,
			@RequestParam(value = "notebookName", required = true) String notebookName) {
			ResponseResult result = new ResponseResult();
			result.setSucceeded(true);
			Notebook notebook = this.notebookService.getNotebookById(id);
			notebook.setNotebookName(notebookName);
			try {
				this.notebookService.updateNotebookInfo(notebook);
			} catch (Exception e) {
				result.setSucceeded(false);
				result.setMessage(e.getMessage());
			}
			return result;
	}
	
	@RequestMapping(value = "/delete/{id}")
	public ResponseResult deleteNotebook(@PathVariable Integer id) {
			ResponseResult result = new ResponseResult();
			result.setSucceeded(true);
			try {
				this.notebookService.deleteNotebook(id);
			} catch (Exception e) {
				result.setSucceeded(false);
				result.setMessage(e.getMessage());
			}
			return result;
	}

}
